<template>
  <div class="caozuo-container" v-loading="isloading">
    <div class="header">
      <div><i class="el-icon-d-arrow-right"></i>设备授权申请</div>
    </div>
    <div class="caozuo">
      <!-- <div class="uploadshebeifile">
        <div class="tips">请选择关联村庄：</div>
        <el-cascader
          style="width: 350px"
          v-model="citySelected"
          :options="countyList"
          :props="props"
          size="medium"
          placeholder="请选择关联村庄"
          clearable
          collapse-tags
          :show-all-levels="false"
          @change="handleChange"
          v-if="citySelectedShow"
        ></el-cascader>
      </div> -->
      <div class="linkerul" v-if="citySelected != []">
        <div class="tip">
          <i class="el-icon-star-on" style="color: red; margin-right: 5px"></i
          >请填写项目负责人和联系电话（一村对应一个项目负责人 !必填）
        </div>
        <ul>
          <li v-for="(domains, index) in citySelected" :key="index">
            <div>{{ domains[domains.length - 1].split(",")[1] }}</div>
            <el-input
              v-model="contactList[index].name"
              placeholder="请输入联系人"
            ></el-input>
            <el-input
              v-model="contactList[index].phone"
              placeholder="请输入联系电话"
            ></el-input>
          </li>
        </ul>
      </div>

      <div class="uploadshebeifile">
        <div class="tips">请上传设备信息附件以及中标合同：</div>
        <el-upload
          class="upload-demo demo1"
          action=""
          :limit="1"
          :http-request="sdsc1"
          :show-file-list="true"
          :file-list="fileList1"
        >
          <el-badge value="必选" class="item">
            <el-tooltip
              class="item"
              effect="dark"
              content="请上传设备信息"
              placement="top-start"
            >
              <el-button size="small" type="primary" plain
                ><i class="el-icon-s-platform"></i>设备信息</el-button
              >
            </el-tooltip>
          </el-badge>
        </el-upload>
        <el-upload
          class="upload-demo demo1"
          action=""
          :limit="1"
          :http-request="sdsc2"
          :show-file-list="true"
          :file-list="fileList2"
        >
          <el-tooltip
            class="item"
            effect="dark"
            content="请上传中标附件"
            placement="top-start"
          >
            <el-button size="small" type="primary" plain
              ><i class="el-icon-s-cooperation"></i>中标合同</el-button
            >
          </el-tooltip>
        </el-upload>
      </div>
      <div class="uploadshebeifile">
        <div class="tips">请填写手机号码以及验证码：</div>
        <div style="display: flex">
          <el-input
            v-model="mobile"
            placeholder="请输入手机号"
            clearable
            @blur="check_mobile"
            prefix-icon="el-icon-phone-outline"
            ><template slot="append"
              ><span @click="send_sms" class="yzmBtn">{{ sms_interval }}</span></template
            ></el-input
          >
          <el-input
            v-model="sms"
            placeholder="请输入验证码"
            clearable
            @blur="check_mobile"
            prefix-icon="el-icon-chat-line-round"
            style="margin-left: 20px"
          ></el-input>
        </div>
      </div>

      <div class="header-right">
        <el-button type="success" plain @click="send" class="buttonmargin"
          ><i class="iconfont icon-tongguo"></i>确定申请</el-button
        >
        <el-tooltip
          class="item"
          effect="dark"
          content="重置"
          placement="bottom"
        >
          <el-button @click="chongzhi" type="danger" icon="el-icon-delete"
            >重置</el-button
          >
        </el-tooltip>
      </div>
    </div>
    <div class="table-bottom">
      <div class="header">
        <div><i class="el-icon-d-arrow-right"></i>设备授权记录</div>
        <!-- <div class="table-tips">
          <i class="el-icon-s-promotion"></i
          >如需补录村庄，请点击表格操作栏中编辑按钮进行补录
        </div> -->
      </div>
      <el-table
        :data="tableData"
        stripe
        @sort-change="sortChange"
        v-loading="isloading"
        border
        style="width: 100%"
        class="eltable"
      >
        <el-table-column label="序号" width="100" type="index" />
        <el-table-column
          prop="applyDate"
          label="申请时间"
          width="180"
          sortable
        />
        <el-table-column prop="applyFiles" label="设备信息">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              content="查看设备信息附件"
              placement="bottom"
            >
              <a :href="getShebeiUrl(scope.row.applyFiles)" download
                ><i class="iconfont icon-shebei"></i
              ></a>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="keyFile" label="中标合同" width="200">
          <template slot-scope="scope">
            <div v-if="scope.row.applyFiles.split(',').length > 1">
              <el-tooltip
                class="item"
                effect="dark"
                content="查看中标合同附件"
                placement="bottom"
              >
                <a
                  :href="getHetongUrl(scope.row.applyFiles)"
                  :download="getHetongUrl(scope.row.applyFiles)"
                  ><i class="iconfont icon-hetong"></i
                ></a>
              </el-tooltip>
            </div>
            <div v-else>无</div>
          </template>
        </el-table-column>
          <el-table-column prop="phone" label="责任人号码" width="150" />
        <el-table-column
          label="操作 "
          width="200"
          fixed="right"
          prop="applyFiles"
        >
          <template scope="scope">
            <el-button
              type="danger"
              @click="handleDelete(scope.row.id)"
              size="mini"
              plain
              ><i class="el-icon-delete"></i>删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="tableData.length > 0"
        class="elpagi"
        :total="total"
        @size-change="getData"
        @current-change="getData"
        @prev-click="getData"
        @next-click="getData"
        :current-page.sync="listquery.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size.sync="listquery.pageSize"
        layout="total,sizes, prev, pager, next, jumper"
      />
    </div>
    <!-- 村庄列表弹出框 -->
    <el-dialog
      title="村庄列表"
      :visible.sync="changeDialogVisible"
      width="30%"
      append-to-body
    >
      <ul class="villageul">
        <div class="allvilagestitle">已选村庄列表如下所示:</div>
        <li v-for="item in allvilages" :key="item">{{ item }}</li>
      </ul>
    </el-dialog>
  </div>
</template>
<script>
import { dataagreenolist, apply, downloadapplyfile } from "@/api/index.js";
import { delrecord,getcode } from "@/api/shenhe.js";
import { getTownList, getAllVillageList } from "@/api/country.js";
import openMixin from "@/mixins/open.js";
import { picHost } from "@/settings.js";
import { handleCofirm } from "@/utils/confirm";
import { mapGetters } from "vuex";
import axios from "axios";
export default {
  computed: {
    ...mapGetters(["citylist"]),
  },
  data() {
    return {
      listquery: {
        pageSize: 10,
        currentPage: 1,
        sortby: null,
        sortorder: null,
      },
      mobile: "",
      sms: "",
 
      is_send: false,
      sms_interval: "获取验证码",
      smsCode: "",
      list: [],
      changeDialogVisible: false,

      allvilages: [],
      citySelected: "",
      props: {},
      fileList1: [],
      fileList2: [],
      tableData: [],
      isloading: false,
      citySelectedShow: true,
      downloadurl: "",
      //contactList: [],
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          let level = node.level;
          if (level == 2) {
            let country = node.label;
            let city = node.parent.label;
            getTownList({
              city: city,
              country: country,
            }).then((res) => {
              let nodes = [];
              let promiseArrary = [];
              res.data.map((v, i) => {
                let n = {
                  id: i,
                  label: v,
                  value: v,
                  children: [],
                };
                let promise = getAllVillageList({
                  city: city,
                  country: country,
                  town: v,
                }).then((response) => {
                  return response;
                });
                promiseArrary.push(promise);
                nodes.push(n);
              });
              Promise.all(promiseArrary).then((dataArr) => {
                nodes.forEach((v, i) => {
                  let data = dataArr[i];
                  v.children = data.data.map((item, index) => {
                    return {
                      id: index,
                      label: item.name,
                      value: item.id + "," + item.name,
                      leaf: true,
                    };
                  });
                });
                resolve(nodes);
              });
            });
          } else {
            resolve(node);
          }
        },
        multiple: true,
      },
    };
  },
  mixins: [openMixin],
  mounted() {
    this.getData();
    downloadapplyfile().then((res) => {
      this.downloadurl = res;
    });
  },
  methods: {
    handleChange(e) {
      this.contactList = [];
      for (let i = 0; i < e.length; i++) {
        this.contactList.push({
          name: "",
          phone: "",
        });
      }
    },
    check_mobile() {
      if (!this.mobile) return;
      var myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      var myreg1 = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
      if (myreg.test(this.mobile) || myreg1.test(this.mobile)) {
        this.is_send = true;
      } else {
        this.$message({
          message: "手机号验证失败",
          type: "warning",
          duration: 1000,
          onClose: () => {
            this.mobile = "";
          },
        });
        return false;
      }
    },
    send_sms() {
      if (!this.is_send) return;
      this.is_send = false;
      let sms_time = 60;
      this.sms_interval = "发送中....";
      let timer = setInterval(() => {
        if (sms_time <= 1) {
          clearInterval(timer);
          this.sms_interval = "获取验证码";
          this.is_send = true;
        } else {
          sms_time -= 1;
          this.sms_interval = `请${sms_time}秒后再发`;
        }
      }, 1000);
    
      getcode(this.mobile).then((res)=>{
      
      }).catch((error) => {
            this.$notify.error({
              title: "错误",
              message: error,
            });
      });;
    },


    
    handleDelete(id) {
      handleCofirm("确认要删除吗？", "warning").then((res) => {
        delrecord(id)
          .then((v) => {
            this.getData();
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
            });
            this.isDialogShow = false;
          })
          .catch((error) => {
            this.$notify.error({
              title: "错误",
              message: error,
            });
          });
      });
    },
    chongzhi() {
      this.list = [];
      this.citySelected = "";
      this.fileList1 = [];
      this.fileList2 = [];
        this.mobile = "";
        this.sms=""
      this.citySelectedShow = false;
      this.$nextTick(() => {
        this.citySelectedShow = true;
      });
    },
    openmore(villages) {
      this.changeDialogVisible = true;
      this.allvilages = villages;
    },
    downloadsoft() {
      window.open(picHost + this.downloadurl.data);
    },
    async getAllVillageList() {
      let res = await getAllVillageList();
    },
    sdsc1(data) {
      let file = data.file;
      let name = file.name;
      let fileType = name.split(".")[name.split(".").length - 1];
      if (fileType != "zip") {
        this.$message.error("仅支持zip格式");
        return;
      }
      this.list.unshift(file);
    },
    sdsc2(data) {
      let file = data.file;
      let name = file.name;
      let fileType = name.split(".")[name.split(".").length - 1];
      if (fileType != "zip") {
        this.$message.error("仅支持zip格式");
        return;
      }
      this.list.push(file);
    },
    send() {
      // this.contactList.forEach((element) => {
      //   if (element.name == "" || element.phone == "") {
      //     this.$notify.error({
      //       title: "错误",
      //       message: "每个村的项目负责人和联系电话必须填写完整",
      //     });
      //     return;
      //   }
      // });

      if(this.mobile==""||this.sms==""){
         this.$notify.error({
              title: "错误",
              message: "手机号，验证码不能为空",
        });
        return
      }
  

      if (this.list.length == 0) {
        this.$notify.error({
          title: "错误",
          message: "请上传设备信息，附件材料",
        });
        return;
      } else {
        var data = new FormData();
        this.list.map((v) => {
          data.append("files", v);
        });
          data.append("phone", this.mobile);
          data.append("code", this.sms);
        // if (this.citySelected != []) {
        //   let datalist = [];
        //   this.citySelected.forEach((element, i) => {
        //     let viresult = element[element.length - 1];
        //     let viresultlist = viresult.split(",");
        //     let villageobj = {
        //       id: viresultlist[0],
        //       village: viresultlist[1],
        //       // name: this.contactList[i].name,
        //       //  phone: this.mobile,
        //       //  code:this.sms
        //     };
        //     datalist.push(villageobj);
        //   });
        //   data.append("data", JSON.stringify(datalist));
        // } else {
        //   data.append("data", []);
        // }
        this.isloading = true;
        apply(data).then((v) => {
          if (v.success) {
            this.$notify({
              title: "成功",
              message: "上传成功",
              type: "success",
            });

            this.getData();
            this.chongzhi();
          } else {
            this.$notify.error({
              title: "错误",
              message: v.message,
            });
          }
          this.isloading = false;
        });
      }
     
    },
    //表格属性排序
    sortChange(data) {
      const { prop, order } = data;
      if (prop == "applyDate") {
        this.listquery.sortby = "createTime";
      } else {
        this.listquery.sortby = prop;
      }

      this.listquery.sortorder = order;
      this.getData();
    },
    async getData() {
      this.isloading = true;
      let res = await dataagreenolist(this.listquery);
      this.tableData = res.data.content;
      this.total = res.data.totalElements;
      this.isloading = false;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../../public/css/table.scss";
.villageul {
  margin: 0;
  padding: 5px;
  list-style: none;
  border: 1px dashed #ccc;
  max-height: 250px;
  overflow-y: auto;
  li {
    line-height: 25px;
  }
}
.allvilagestitle {
  line-height: 35px;
  color: #4778c7;
}
::v-deep .el-input-group__append{
    color: #1890ff;
    background: #e8f4ff;
    border-color: #a3d3ff;
    cursor: pointer;
}
::v-deep .el-dialog__title {
  font-size: 16px;
  color: #4cc8c7;
}
::v-deep .el-dialog__body {
  padding: 10px 20px;
  margin-top: -10px;
}
.caozuo-container {
  margin: 5px;
  padding-bottom: 10px;
  overflow: auto;
  position: relative;
  height: 100%;
}
.table-bottom {
  margin-top: 20px;
  .header {
    border-bottom: none;
  }
}
.table-tips {
  font-size: 14px;
  font-weight: 600;
}
.more {
  color: #4cc8c7;
  margin-left: 10px;
  &:hover {
    color: orange;
  }
}
.vitotal {
  margin-left: 4px;
  color: #9370db;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  text-align: left;
  letter-spacing: 1px;
  font-size: 15px;
  font-weight: 500;
  line-height: 25px;
  padding: 5px;
  border-bottom: 1px dashed #ccc;
  .header-button {
    padding: 5px;
    border-radius: 50%;
  }

  i {
    font-size: 18px;
    color: #4cc8c7;
  }
}
.caozuo {
  .uploadshebeifile {
    display: flex;
    align-items: center;
    margin: 10px 20px;
    .tips {
      font-size: 14px;
      margin-right: 15px;
    }
    .upload-demo {
      display: flex;
      align-items: center;
    }
    .demo1 {
      margin-right: 30px;
    }
  }
  .linkerul {
    margin: 15px 0px;
    padding-bottom: 10px;
    ul {
      margin: 10px 0px;
      padding-top: 10px;
      border: none;
      list-style: none;
      max-height: 210px;
      overflow-y: auto;
    }

    .tip {
      font-size: 14px;
      display: flex;
      align-items: center;
    }
    li {
      display: flex;
      justify-content: left;

      div {
        padding: 10px 20px;
        width: 350px;
      }
    }
  }
  .header-right {
    border-top: 1px dashed #ccc;
    padding-top: 15px;
    text-align: right;
  }
}
</style>